﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework;
using SharedTypes;

namespace CustomContent
{
	[ContentProcessor]
	public class FModelProcessor : ModelProcessor
	{
		private List<object> meshParts = new List<object>();

		public override ModelContent Process(NodeContent input, ContentProcessorContext context)
		{
			ModelContent model = base.Process(input, context);

			FindVertices(input, null);

			model.Tag = meshParts;

			return model;
		}

		void FindVertices(NodeContent node, MeshPart parent)
		{
            //System.Diagnostics.Debugger.Break();
			// Is this node a mesh?
			MeshContent mesh = node as MeshContent;
			MeshPart tempPart = null;

			if (mesh != null)
			{
				// Look up the absolute transform of the mesh.
				Matrix absoluteTransform = mesh.AbsoluteTransform;

				// Loop over all the pieces of geometry in the mesh.
				foreach (GeometryContent geometry in mesh.Geometry)
				{
                    MeshPart part = new MeshPart(mesh.Name, mesh.Identity != null ? mesh.Identity.FragmentIdentifier : null);
                    tempPart = part;
                    part.Parent = parent;
                    part.AbsoluteTransform = mesh.AbsoluteTransform;
                    part.Transform = mesh.Transform;

					// Loop over all the indices in this piece of geometry.
					// Every group of three indices represents one triangle.
					foreach (int index in geometry.Indices)
					{
						part.Indices.Add(index);
					}

					var verts = geometry.Vertices.Positions;
					for (int i = 0; i < geometry.Vertices.Positions.Count; i++)
					{
						var v = Vector3.Transform(verts[i], absoluteTransform);
						part.Vertices.Add(v);
					}

                    meshParts.Add(part);
				}
			}

			// Recursively scan over the children of this node.
			foreach (NodeContent child in node.Children)
			{
				FindVertices(child, tempPart);
			}
		}
	}
}
